package com.example.micro.netty.server.nio.channel;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 本地文件读 demo
 */
public class NIOFileChannelDemo2 {

    public static void main(String[] args) throws IOException {

        //创建一个输入流 -> channel || 为什么是FileOutputStream？原生的输出流内置了通道
        File file = new File("/Users/didi/IdeaProjects/nio_file_demo1.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        //同理写法
        //FileInputStream fileInputStream = new FileInputStream("/Users/didi/IdeaProjects/nio_file_demo1.txt");

        FileChannel fileChannel = fileInputStream.getChannel();

        //此时默认为写入模式,大小设置file长度不浪费资源
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());

        //将fileChannel中的数据读出，并写入到byteBuffer中
        fileChannel.read(byteBuffer);

        System.out.println(new String(byteBuffer.array()));

        //因为当前byteBuffer为写模式，如果想byteBuffer.get()获取，必须先flip
        byteBuffer.flip();
        for (int i = 0; i < byteBuffer.limit(); i++) {
            System.out.println((char) byteBuffer.get());
        }

        fileInputStream.close();

    }

}
